package com.zhugang.week04;

/**
 * @program algorithms
 * @description: sortArrayByParity
 * @author: chanzhugang
 * @create: 2022/06/27 15:45
 */
public class SortArrayByParity2 {

    public static void main(String[] args) {
        SortArrayByParity2 sortArrayByParity2 = new SortArrayByParity2();
        int[] a = new int[]{1, 4, 3, 2};
        int[] res = sortArrayByParity2.sortArrayByParity(a);
        for (int num : res) {
            System.out.println(num);
        }
    }

    /**
     * 905. 按奇偶排序数组
     *
     * @param nums
     * @return
     */
    public int[] sortArrayByParity(int[] nums) {
        // 双指针i、j，i是偶数++，j是奇数--,否则交换
        int i = 0;
        int j = nums.length - 1;
        while (i < j) {
            if (nums[i] % 2 == 0) {
                i++;
                continue;
            }
            if (nums[j] % 2 == 1) {
                j--;
                continue;
            }
            swap(nums, i, j);
            i++;
            j--;
        }
        return nums;
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}